package com.yukh.framework.base.net.socket.demo4;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

class Daemon implements Runnable {
	private final Selector selector;

	Daemon(Selector selector) {
		this.selector = selector;
	}

	public void run() {
		while (true) {
			try {
				// Wait for an event
				selector.select();

				// Get list of selection keys with pending events
				Iterator<SelectionKey> it = selector.selectedKeys().iterator();

				// Process each key
				while (it.hasNext()) {
					// Get the selection key
					SelectionKey selKey = it.next();

					// Remove it from the list to indicate that it is being
					// processed
					it.remove();

					// Check if it's a connection request
					if (selKey.isAcceptable()) {
						// Get channel with connection request
						ServerSocketChannel server = (ServerSocketChannel) selKey
								.channel();
						// Accept the connection request.
						// If serverSocketChannel is blocking, this method
						// blocks.
						// The returned channel is in blocking mode.
						SocketChannel channel = server.accept();

						// If serverSocketChannel is non-blocking, sChannel may
						// be null
						if (channel != null) {
							// Use the socket channel to communicate with the
							// client
							new Thread(new ServerHandler(channel)).start();
						} else {
							System.out.println("---No Connection---");
							// There were no pending connection requests; try
							// again later.
							// To be notified of connection requests,
						}
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
}
